import com.mysql.jdbc.MySQLConnection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class dome {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学号:");
        int id = scanner.nextInt();
        System.out.println("请输入姓名:");
        String name = scanner.next();
        //1.创建datasource
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");
        //2.建立和数据库服务器的连接
        Connection connection = dataSource.getConnection();
        //3.构造sql

        //String sql = "insert into student values (2, '王五')";  //插入数据
        String sql = "insert into student values (?, ?)";  //插入数据
       // String sql = "delete from student where name = '王五'";  //删除数据

        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);
        System.out.println("sql = "+statement);
        //4.把sql发送服务器,返回值是一个整数,表示影响到的行数
        int n = statement.executeUpdate();
        System.out.println("n ="+n);
        //5.关闭连接,释放资源,后创建的先释放
        statement.close();
        connection.close();
    }
}
